<template>
	<view class="detail-page">
		<!-- 轮播图 -->
		<swiper class="banner-swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500"
			indicator-color="rgba(255, 255, 255, 0.5)" indicator-active-color="#ffffff">
			<swiper-item v-for="(image, index) in houseImages" :key="index">
				<image :src="image" mode="aspectFill" class="banner-image"></image>
			</swiper-item>
		</swiper>

		<!-- 房源信息 -->
		<view class="house-info">
			<!-- 标题 -->
			<view class="house-title">{{ houseDetail.title }}</view>

			<!-- 标签 -->
			<view class="house-tags">
				<view class="tag" v-for="(tag, index) in houseTags" :key="index">{{ tag }}</view>
			</view>

			<!-- 主要信息卡片 -->
			<view class="info-cards">
				<view class="info-card">
					<view class="info-value">{{ houseDetail.price }}<text class="unit">/月</text></view>
					<view class="info-label">租金</view>
				</view>
				<view class="info-card">
					<view class="info-value">{{ houseDetail.roomType }}</view>
					<view class="info-label">房型</view>
				</view>
				<view class="info-card">
					<view class="info-value">{{ houseDetail.size }}<text class="unit">平方</text></view>
					<view class="info-label">面积</view>
				</view>
			</view>

			<!-- 详细信息 -->
			<view class="detail-info">
				<view class="detail-row">
					<view class="detail-cell">
						<text class="detail-label">装修：</text>
						<text class="detail-value">{{ formatValue(houseDetail.renovation) }}</text>
					</view>
					<view class="detail-cell">
						<text class="detail-label">朝向：</text>
						<text class="detail-value">{{ formatValue(houseDetail.oriented) }}</text>
					</view>
				</view>
				<view class="detail-row">
					<view class="detail-cell">
						<text class="detail-label">楼层：</text>
						<text class="detail-value">{{ formatValue(houseDetail.floor) }}</text>
					</view>
					<view class="detail-cell">
						<text class="detail-label">类型：</text>
						<text class="detail-value">{{ formatValue(houseDetail.houseType, '普通住宅') }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 小区信息 -->
		<view class="community-info">
			<view class="section-title">小区：{{ houseDetail.community || '暂无' }}</view>

			<!-- 地图 -->
			<view class="map-container">
				<!-- #ifdef H5 -->
				<view id="house-map" class="map"></view>
				<!-- #endif -->

				<!-- #ifdef MP-WEIXIN -->
				<map class="map" :latitude="mapCenter.latitude" :longitude="mapCenter.longitude" :scale="16"
					:markers="mapMarkers" :show-location="false">
				</map>
				<!-- #endif -->
			</view>
		</view>

		<!-- 房屋配套 -->
		<view class="facilities-section" v-if="facilities && facilities.length > 0">
			<view class="section-title">房屋配套</view>
			<view class="facilities-grid">
				<view class="facility-item" v-for="(item, index) in facilities" :key="index">
					<view class="facility-icon">{{ getFacilityIcon(item) }}</view>
					<text class="facility-name">{{ item }}</text>
				</view>
			</view>
		</view>

		<!-- 房屋概况 -->
		<view class="overview-section" v-if="houseDetail.description">
			<view class="section-title">房屋概况</view>
			
			<!-- 房东信息 -->
			<view class="landlord-info" v-if="landlordInfo">
				<view class="landlord-avatar">
					<image v-if="landlordInfo.avatar && landlordInfo.avatar.startsWith('http')" 
						:src="landlordInfo.avatar" class="avatar-img" mode="aspectFill"></image>
					<text v-else class="avatar-text">👤</text>
				</view>
				<view class="landlord-details">
					<view class="landlord-name">{{ landlordInfo.name }}</view>
					<view class="landlord-verified" v-if="landlordInfo.verified">
						<text class="verified-badge">✓</text>
						<text>已认证房主</text>
					</view>
				</view>
				<view class="contact-btn" @click="contactLandlord">
					<text>发消息</text>
				</view>
			</view>

			<!-- 房屋描述 -->
			<view class="description-content">
				<text class="description-text">{{ houseDetail.description }}</text>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="collect-btn" @click="toggleCollect">
				<image src="/static/收藏.png" class="collect-icon" :class="{ 'collected': isCollected }"></image>
				<text class="collect-text" :class="{ 'collected-text': isCollected }">{{ isCollected ? '已收藏' : '收藏' }}</text>
			</view>
			<view class="consult-btn" @click="onlineConsult">
				<text>在线咨询</text>
			</view>
			<view class="reserve-btn" @click="phoneReserve">
				<text>电话预定</text>
			</view>
		</view>
	</view>
</template>

<script>
	import { baseUrl } from '@/context/config.js'
	export default {
	data() {
		return {
			houseCode: '',
			houseDetail: {},
			houseImages: [],
			houseTags: [],
			facilities: [],
			landlordInfo: null,
			isCollected: false,
			mapCenter: {
				latitude: 39.9,
				longitude: 116.4
			},
			mapMarkers: []
		}
	},
	onLoad(options) {
		if (options.houseCode) {
			this.houseCode = options.houseCode;
			this.getHouseDetail();
			this.checkCollectStatus();
		}
	},
	methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			// 获取房源详情
		async getHouseDetail() {
			uni.showLoading({ title: '加载中...' });

			try {
				const res = await uni.request({
				url: `${baseUrl}/houses/${this.houseCode}`,
				method: 'GET'
			});

				if (res.statusCode === 200) {
					const data = res.data.body || res.data.data || res.data;

					this.houseDetail = {
						title: data.title || '',
						price: data.price || 0,
						roomType: data.roomTxt || data.room || '',
						size: data.size || 0,
						renovation: data.renovation || '',
						oriented: data.oriented || '',
						floor: data.floor || '',
						houseType: data.houseType || '普通住宅',
						community: data.community || '',
						description: data.description || '',
						coord: data.coord || {}
					};

					// 处理图片
					if (data.houseImg) {
						if (Array.isArray(data.houseImg)) {
							this.houseImages = data.houseImg
								.filter(img => img && typeof img === 'string' && img.trim()) // 过滤空值和无效字符串
								.map(img => {
									const trimmedImg = img.trim();
									// 确保图片路径有效且不以斜杠结束
									if (trimmedImg.startsWith('http')) {
										return trimmedImg;
									} else {
										// 避免生成类似http://localhost:8080/的无效路径
									return trimmedImg ? `${baseUrl}${trimmedImg}` : '';
									}
								})
								.filter(img => img); // 再次过滤可能产生的空字符串
						} else if (typeof data.houseImg === 'string') {
							const trimmedImg = data.houseImg.trim();
							if (trimmedImg) {
								const imgUrl = trimmedImg.startsWith('http')
							? trimmedImg
							: `${baseUrl}${trimmedImg}`;
								this.houseImages = [imgUrl];
							} else {
								this.houseImages = [];
							}
						}
					}

					// 处理标签
					if (data.tags) {
						this.houseTags = this.parseTags(data.tags);
					}

					// 处理配套设施
					if (data.supporting) {
						this.facilities = this.parseFacilities(data.supporting);
					}

					// 处理房东信息
					if (data.user) {
						this.landlordInfo = {
							name: data.user.nickname || data.user.name || '张女士',
							avatar: data.user.avatar || '',
							verified: data.user.verified || false
						};
					} else {
						// 默认房东信息
						this.landlordInfo = {
							name: '张女士',
							avatar: '',
							verified: true
						};
					}

					// 设置地图位置
					if (data.coord) {
						this.mapCenter = {
							latitude: parseFloat(data.coord.latitude) || 39.9,
							longitude: parseFloat(data.coord.longitude) || 116.4
						};

						this.mapMarkers = [{
							id: 1,
							latitude: this.mapCenter.latitude,
							longitude: this.mapCenter.longitude,
							iconPath: '/static/位置.png',
							width: 30,
							height: 30,
							callout: {
								content: this.houseDetail.community || '房源位置',
								color: '#333333',
								fontSize: 12,
								borderRadius: 8,
								bgColor: '#ffffff',
								padding: 8,
								display: 'ALWAYS'
							}
						}];

						// H5地图初始化
						// #ifdef H5
						this.$nextTick(() => {
							this.initBaiduMap();
						});
						// #endif
					}
				}

				// 数据加载成功后，保存浏览记录
				this.saveViewRecord();

			} catch (error) {
				console.error('获取房源详情失败:', error);
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		},

		// 保存浏览记录
		saveViewRecord() {
			if (!this.houseCode || !this.houseDetail.title || !this.houseDetail.price) {
				return;
			}

			try {
				let viewRecords = uni.getStorageSync('viewRecords') || [];
				const existIndex = viewRecords.findIndex(item => item.houseCode === this.houseCode);
				
				const recordItem = {
			houseCode: this.houseCode,
			title: this.houseDetail.title || '未知',
			price: this.houseDetail.price || 0,
			roomType: this.houseDetail.roomType || '未知',
			size: this.houseDetail.size || 0,
			image: this.houseImages && this.houseImages[0] ? this.houseImages[0] : '',
			community: this.houseDetail.community || '未知',
			floor: this.houseDetail.floor || '未知',
			oriented: this.houseDetail.oriented || '未知',
			viewTime: new Date().getTime()
		};

				if (existIndex !== -1) {
					viewRecords.splice(existIndex, 1);
				}

				viewRecords.unshift(recordItem);

				if (viewRecords.length > 100) {
					viewRecords = viewRecords.slice(0, 100);
				}

				uni.setStorageSync('viewRecords', viewRecords);
			} catch (e) {
				console.error('保存浏览记录失败:', e);
			}
		},

		// 解析标签
		parseTags(tags) {
			if (!tags) return [];
			if (Array.isArray(tags)) return tags;
			if (typeof tags === 'string') {
				return tags.split(',').filter(tag => tag.trim());
			}
			return [];
		},

		// 格式化值（处理数组、空值等）
		formatValue(value, defaultValue = '未知') {
			if (!value) return defaultValue;
			if (Array.isArray(value)) {
				return value.length > 0 ? value.join('、') : defaultValue;
			}
			if (typeof value === 'string') {
				return value.trim() || defaultValue;
			}
			return String(value) || defaultValue;
		},

		// 解析配套设施
		parseFacilities(supporting) {
			if (!supporting) return [];
			if (Array.isArray(supporting)) return supporting;
			if (typeof supporting === 'string') {
				// 如果是逗号分隔的字符串
				return supporting.split(',').filter(item => item.trim());
			}
			return [];
		},

		// 获取配套设施图标（使用emoji）
		getFacilityIcon(name) {
			const iconMap = {
				'衣柜': '🗄',
				'洗衣机': '🛁',
				'天然气': '☁',
				'冰箱': '🗄',
				'电视': '📺',
				'热水器': '🚿',
				'宽带': '📇',
				'沙发': '🛋️',
				'空调': '❄️',
				'暖气': '🌡️',
				'床': '🛏️',
				'燃气灶': '🔥',
				'wifi': '📶',
				'WiFi': '📶',
				'WIFI': '📶'
			};
			return iconMap[name] || '✨';
		},

		// 联系房东
		contactLandlord() {
			uni.showToast({
				title: '正在打开聊天窗口...',
				icon: 'none'
			});
		},

		// 初始化百度地图（H5）
		initBaiduMap() {
			// #ifdef H5
			if (typeof BMapGL === 'undefined') return;

			const map = new BMapGL.Map('house-map');
			const point = new BMapGL.Point(this.mapCenter.longitude, this.mapCenter.latitude);
			map.centerAndZoom(point, 16);
			map.enableScrollWheelZoom(true);

			// 添加标记
			const marker = new BMapGL.Marker(point);
			map.addOverlay(marker);

			// 添加信息窗口
			const infoWindow = new BMapGL.InfoWindow(this.houseDetail.community || '房源位置', {
				width: 200,
				height: 50
			});
			marker.addEventListener('click', () => {
				map.openInfoWindow(infoWindow, point);
			});
			// #endif
		},

		// 检查收藏状态
		checkCollectStatus() {
			try {
				// 获取存储的token
				const token = uni.getStorageSync('token');
				
				// 如果没有token，不检查收藏状态
				if (!token) {
					this.isCollected = false;
					return;
				}
				
				// 发送请求到接口获取收藏状态
		uni.request({
			url: `${baseUrl}/user/favorites/${this.houseCode}`,
			method: 'GET',
			header: {
				'Authorization': token
			},
				success: (res) => {
					if (res.statusCode === 200 && res.data && res.data.status === 200) {
						this.isCollected = res.data.body?.isFavorite || false;
					} else {
						this.isCollected = false;
					}
				},
				fail: (err) => {
					console.error('获取收藏状态失败:', err);
					this.isCollected = false;
				}
			});
			} catch (e) {
				console.error('检查收藏状态失败:', e);
				this.isCollected = false;
			}
		},

		// 切换收藏状态
		toggleCollect() {
			try {
				// 获取存储的token
				const token = uni.getStorageSync('token');
				
				// 如果没有token，提示用户登录
				if (!token) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				
				if (this.isCollected) {
				// 取消收藏
				uni.request({
					url: `${baseUrl}/user/favorites/${this.houseCode}`,
					method: 'DELETE',
					header: {
							'Authorization': token
					},
						success: (res) => {
							if (res.statusCode === 200 && res.data && res.data.status === 200) {
								this.isCollected = false;
								uni.showToast({
									title: '取消收藏成功',
									icon: 'success'
								});
							} else {
								uni.showToast({
									title: res.data?.description || '取消收藏失败',
									icon: 'none'
								});
							}
						},
						fail: (err) => {
							console.error('取消收藏失败:', err);
							uni.showToast({
								title: '网络错误，请重试',
								icon: 'none'
							});
						}
					});
				} else {
					// 验证必要数据
					if (!this.houseDetail.title || !this.houseDetail.price) {
						uni.showToast({
							title: '房源信息不完整',
							icon: 'none'
						});
						return;
					}

					// 获取第一张图片，并确保路径正确
					let firstImage = '/static/logo.png'; // 默认图片
					if (this.houseImages && Array.isArray(this.houseImages) && this.houseImages.length > 0) {
						firstImage = this.houseImages[0];
						// 确保图片路径格式正确
				if (typeof firstImage === 'string' && !firstImage.startsWith('http') && !firstImage.startsWith('/')) {
					firstImage = baseUrl + firstImage;
				}
					}

					// 构建搜索页面格式的数据
					const description = `${this.houseDetail.roomType || ''} ${this.houseDetail.size || ''}平米 ${this.houseDetail.floor || ''} ${this.houseDetail.oriented || ''}`.trim();
					
					// 准备收藏数据
				const collectData = {
					houseCode: this.houseCode,
					title: this.houseDetail.title || '未知房源',
					desc: description,
					price: this.houseDetail.price || 0,
					houseImg: firstImage,
					community: this.houseDetail.community || '未知小区'
				};
				
					console.log('收藏的数据:', collectData);
					
					// 添加收藏
				uni.request({
					url: `${baseUrl}/user/favorites/${this.houseCode}`,
					method: 'POST',
				header: {
					'Authorization': token,
					'Content-Type': 'application/json'
				},
				data: collectData,
				success: (res) => {
					if (res.statusCode === 200 && res.data && res.data.status === 200) {
						this.isCollected = true;
						uni.showToast({
							title: '收藏成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: res.data?.description || '收藏失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					console.error('收藏失败:', err);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				}
			});
				}
			} catch (e) {
				console.error('收藏操作失败:', e);
				uni.showToast({
					title: '操作失败',
					icon: 'none'
				});
			}
		},

		// 在线咨询
		onlineConsult() {
			uni.showToast({
				title: '正在联系房东...',
				icon: 'none'
			});
		},

		// 电话预定
		phoneReserve() {
			uni.showModal({
				title: '电话预定',
				content: '是否拨打电话：400-800-8888',
				success: (res) => {
					if (res.confirm) {
						uni.makePhoneCall({
							phoneNumber: '4008008888'
						});
					}
				}
			});
		}
	}
}
</script>

<style scoped>


/* 轮播图 */
.banner-swiper {
	width: 100%;
	height: 500rpx;
	margin-top: 88rpx; /* 为自定义导航栏留出空间 */
}

.banner-image {
	width: 100%;
	height: 100%;
}

/* 房源信息 */
.house-info {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.house-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	line-height: 1.5;
	margin-bottom: 20rpx;
}

.house-tags {
	display: flex;
	flex-wrap: wrap;
	gap: 15rpx;
	margin-bottom: 30rpx;
}

.tag {
	padding: 10rpx 24rpx;
	font-size: 24rpx;
	color: #21B97A;
	background-color: #E8F5F1;
	border-radius: 30rpx;
	font-weight: 500;
}

.tag:nth-child(1) {
	background: linear-gradient(135deg, #E8F5F1 0%, #D4EFE6 100%);
}

.tag:nth-child(2) {
	background: linear-gradient(135deg, #FFF3E0 0%, #FFE4C4 100%);
	color: #FF9800;
}

/* 信息卡片 */
.info-cards {
	display: flex;
	justify-content: space-between;
	margin-bottom: 30rpx;
	padding: 30rpx 0;
	border-top: 1rpx solid #f0f0f0;
	border-bottom: 1rpx solid #f0f0f0;
}

.info-card {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	position: relative;
}


.info-value {
	font-size: 40rpx;
	color: #FF5252;
	font-weight: bold;
	line-height: 1.2;
	margin-bottom: 10rpx;
}

.info-value .unit {
	font-size: 24rpx;
	font-weight: normal;
}

.info-label {
	font-size: 26rpx;
	color: #999;
}

/* 详细信息 */
.detail-info {
	padding-top: 30rpx;
}

.detail-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 30rpx;
}

.detail-row:last-child {
	margin-bottom: 0;
}

.detail-cell {
	flex: 1;
	display: flex;
	align-items: center;
	font-size: 28rpx;
	padding-left: 60rpx;
}

.detail-label {
	color: #FF5252;
	font-weight: 500;
	margin-right: 10rpx;
	white-space: nowrap;
}

.detail-value {
	color: #333;
	font-weight: 400;
}

/* 小区信息 */
.community-info {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 32rpx;
	color: #21B97A;
	font-weight: 600;
	margin-bottom: 24rpx;
	padding-left: 20rpx;
	border-left: 6rpx solid #21B97A;
}

.map-container {
	width: 100%;
	height: 500px;
	border-radius: 8rpx;
	overflow: hidden;
}

.map {
	width: 100%;
	height: 100%;
}

/* 底部操作栏 */
.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	align-items: center;
	gap: 20rpx;
	background-color: #fff;
	padding: 20rpx 30rpx;
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.08);
	z-index: 999;
}

.collect-btn {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	width: 140rpx;
	height: 90rpx;
	background-color: #fff;
	border: 2rpx solid #ddd;
	border-radius: 50rpx;
	font-size: 24rpx;
	color: #333;
}

.collect-icon {
	width: 36rpx;
	height: 36rpx;
	margin-bottom: 4rpx;
	transition: all 0.3s ease;
}

.collect-icon.collected {
	/* 使用CSS滤镜将绿色转为红色 */
	filter: brightness(0) saturate(100%) invert(38%) sepia(87%) saturate(4780%) hue-rotate(355deg) brightness(116%) contrast(112%);
}

.collect-text.collected-text {
	color: #ff5252;
}

.collect-text {
	font-size: 24rpx;
}

.consult-btn {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	height: 90rpx;
	background: linear-gradient(135deg, #5FD5B4 0%, #21B97A 100%);
	color: #fff;
	border-radius: 50rpx;
	font-size: 32rpx;
	font-weight: 500;
}

.reserve-btn {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	height: 90rpx;
	background: linear-gradient(135deg, #21B97A 0%, #1A9861 100%);
	color: #fff;
	border-radius: 50rpx;
	font-size: 32rpx;
	font-weight: 500;
}

/* 房屋配套 */
.facilities-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.facilities-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 30rpx;
	margin-top: 20rpx;
}

.facility-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	gap: 15rpx;
}

.facility-icon {
	width: 80rpx;
	height: 80rpx;
	font-size: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #f5f7fa;
	border-radius: 12rpx;
}

.facility-name {
	font-size: 24rpx;
	color: #666;
	text-align: center;
}

/* 房屋概况 */
.overview-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.landlord-info {
	display: flex;
	align-items: center;
	padding: 20rpx;
	background-color: #f8f9fa;
	border-radius: 12rpx;
	margin-bottom: 30rpx;
}

.landlord-avatar {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	margin-right: 20rpx;
	background-color: #e8f5f1;
	display: flex;
	align-items: center;
	justify-content: center;
	overflow: hidden;
}

.avatar-img {
	width: 100%;
	height: 100%;
}

.avatar-text {
	font-size: 50rpx;
}

.landlord-details {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 10rpx;
}

.landlord-name {
	font-size: 32rpx;
	color: #E64A19;
	font-weight: 600;
}

.landlord-verified {
	display: flex;
	align-items: center;
	gap: 8rpx;
	font-size: 24rpx;
	color: #21B97A;
}

.verified-badge {
	width: 28rpx;
	height: 28rpx;
	background-color: #21B97A;
	color: #fff;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 20rpx;
	font-weight: bold;
}

.contact-btn {
	padding: 12rpx 32rpx;
	background-color: #fff;
	color: #21B97A;
	border: 2rpx solid #21B97A;
	border-radius: 50rpx;
	font-size: 26rpx;
	font-weight: 500;
}

.description-content {
	line-height: 1.8;
}

.description-text {
	font-size: 28rpx;
	color: #333;
	line-height: 1.8;
	text-align: justify;
}
</style>
